<template>
  <div class="warningAdmin" v-loading="warningAdminLoading">
    <div class="title">预警管理</div>
    <div class="searchBox">
      <el-form ref="form" :model="searchForm" size="mini" inline>
        <el-row>
          <el-form-item label="预警站点" label-width="90px">
            <!-- <el-input v-model="searchForm.enterpriseName" placeholder="请输入企业名称"></el-input> -->
            <el-select v-model="searchForm.waterStation" placeholder="请选择水站名称" clearable>
              <p v-for="(item, index) of stationList" :key="index">
                <el-option :label="item" :value="item"></el-option>
              </p>
            </el-select>
          </el-form-item>
          <el-form-item label="预警类型" label-width="90px">
            <el-select
              v-model="searchForm.warningType"
              placeholder="请选择预警类型"
              :clearable="!this.userInfo.roles.includes('manager')"
            >
              <p v-for="(item, index) of warningTypes" :key="index">
                <el-option :label="item" :value="item"></el-option>
              </p>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="时间" label-width="60px">
            <el-col :span="11">
              <el-date-picker
                v-model="searchForm.starttime"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="选择开始日期"
              ></el-date-picker>
            </el-col>
            <el-col :span="2" class="line">-</el-col>
            <el-col :span="11">
              <el-date-picker
                v-model="searchForm.lasttime"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="选择结束日期"
              ></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="greenBtn"
              size="mini"
              @click="onSubmit({pageSize: pageSize, pageNum: 1})"
            >确定</el-button>
            <el-tooltip content="批量处理只能选同一种预警类型并且时间间隔不超过6个小时" placement="bottom" effect="light">
              <el-button
                type="primary"
                class="greenBtn"
                size="mini"
                v-show="!userInfo.roles.includes('manager')"
                @click="changeBatchHandle(!isBatchHandle)"
              >{{isBatchHandle ? "关闭" : "开启"}}批量处理</el-button>
            </el-tooltip>
            <el-button type="success" size="mini" v-show="isBatchHandle" @click="batchHandle">批量处理</el-button>
            <!-- <el-button size="mini" >导出</el-button> -->
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="tableBox">
      <el-table
        :data="warningAdmin.data"
        border
        size="mini"
        ref="warningTable"
        style="width: 100%"
        :header-cell-style="{color: '#666', backgroundColor: '#feedcf'}"
        :row-style="checkCanSelect"
        @selection-change="selectionChange"
        @select-all="selectAll"
        :select-on-indeterminate="false"
        :default-sort="{ prop: 'warningTime', order: 'descending' }"
      >
        <el-table-column
          v-if="isBatchHandle"
          type="selection"
          :selectable="checkSelectable"
          align="center"
          width="40"
        ></el-table-column>
        <el-table-column prop="warningId" label="编号" align="center"></el-table-column>
        <el-table-column prop="warningTime" label="预警时间" sortable align="center"></el-table-column>
        <el-table-column prop="warningType" label="预警类型" align="center"></el-table-column>
        <el-table-column prop="warningStation" label="预警站点" align="center"></el-table-column>
        <el-table-column prop="warningContent" label="预警内容" align="center">
          <template slot-scope="scope">
            <el-button type="text" class="openDetailBtn" @click="openDetail(scope.row.warningId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="warningStatus" label="处理状态" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="scope.row.warningStatus === 2"
              @click="openIsHandled(scope.row.warningId)"
            >已处理</el-button>
            <el-button
              type="text"
              class="dangerText"
              v-else
              @click="added(scope.row.warningId)"
            >{{warningStatus[scope.row.warningStatus]}}</el-button>
            <!-- :disabled="userInfo.roles.filter(v => v == 'operator' || v == 'admin').length > 0 ? false : true" -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <myPaging :func="pageUpdate" :total="warningAdmin.total"></myPaging>

    <el-dialog :visible.sync="warnCntVisible" append-to-body>
      <div slot="title">
        <p>预警内容</p>
      </div>
      <h3 style="margin-bottom: 12px;">
        {{curWarnCntDetail.warningTime}}
        {{curWarnCntDetail.warningStation}}
      </h3>
      <div v-if="curWarnCntDetail.warningType === '因子超标预警'">
        <el-table :data="curWarnCntDetail.content" border show-header>
          <el-table-column prop="name" label="因子名称" align="center">
            <template slot-scope="scope">
              <span>{{common.translate(scope.row.name)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="监测值" align="center">
            <template slot-scope="scope">
              <span
                style="color: #e53139"
              >{{scope.row.value}} {{indexOFShowUnit(common.translate(scope.row.name)) ? 'mg / L' : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="超标倍数" align="center">
            <template slot-scope="scope">
              <span
                style="color: #e53139"
              >{{common.multiples(scope.row.value, standard[scope.row.name])}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="curWarnCntDetail.warningType === '设备异常预警'">
        <el-table :data="curWarnCntDetail.content" border :show-header="false">
          <el-table-column prop="name" label="超标因子" align="center">
            <template slot-scope="scope">
              <span>{{common.translate(scope.row.name)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="超标值" align="center">
            <template slot-scope="scope">
              <span
                style="color: #e53139"
              >{{scope.row.value || "异常"}} {{indexOFShowUnit(common.translate(scope.row.name)) ? 'mg / L' : '' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="curWarnCntDetail.warningType === '数据因子缺失'">
        <p class="missWarning" v-for="(item, index) in curWarnCntDetail.content" :key="index">
          {{common.translate(item.name)}}：
          <span
            style="color: #e53139"
            v-show="Array.isArray(item.value)"
            v-for="factor in item.value"
            :key="factor"
          >{{common.translate(factor)}}</span>
          <span style="color: #e53139" v-show="!Array.isArray(item.value)">{{item.value}}</span>
        </p>
      </div>
      <div
        v-if="curWarnCntDetail.warningType === '数据丢失' || curWarnCntDetail.warningType === '设备离线'"
      >
        <p class="missWarning" v-for="item in curWarnCntDetail.content" :key="item.name">
          {{common.translate(item.name)}} :
          <span style="color: #e53139">{{item.value}}</span>
        </p>
      </div>
      <p class="responseCnt">
        <el-button size="small" @click="responseWarning(curWarnCntDetail.warningId)">响应并处理</el-button>
        <!-- v-show="!userInfo.roles.includes('manager')" -->
      </p>
    </el-dialog>
    <el-dialog :visible.sync="isHandledVisible" custom-class="warningAdmin" append-to-body>
      <div slot="title">
        <p>处理结果</p>
      </div>
      <el-form :model="curIsHandledDetail" disabled size="mini" label-width="100px">
        <el-form-item label="处理描述">
          <el-input type="textarea" :rows="4" v-model="curIsHandledDetail.processingMark"></el-input>
        </el-form-item>
        <el-form-item label="现场图片" label-width="100px" style="margin-top: 15px;">
          <viewer :images="curIsHandledDetail.imgList">
            <img
              class="imgItem"
              v-for="(item, index) of curIsHandledDetail.imgList"
              :key="index"
              :src="'http://47.112.16.168:' + item"
            />
          </viewer>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人">
              <el-input v-model="curIsHandledDetail.processingPerson"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-form-item label="处理时间">
          <el-input v-model="curIsHandledDetail.gmtModified"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      width="60%"
      :visible.sync="updateFormVisible"
      @close="clearUpdateForm"
      append-to-body
    >
      <div slot="title">
        <p>{{isBatchHandle ? "批量" : ""}}处理</p>
      </div>
      <el-form
        :model="updateForm"
        :rules="updateFormRules"
        size="mini"
        ref="updateForm"
        label-width="100px"
        v-loading="updateFormLoading"
      >
        <el-form-item label="处理描述" prop="processingMark">
          <el-input
            type="textarea"
            :rows="4"
            v-model="updateForm.processingMark"
            placeholder="请填写处理描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="现场图片" label-width="100px" style="margin-top: 15px;" prop="photoFiles">
          <el-upload
            ref="addUploadPhoto"
            action
            :file-list="updateForm.photoFiles"
            list-type="picture-card"
            multiple
            :limit="4"
            :on-change="uploadChange"
            :on-exceed="uploadExceed"
            :http-request="handleSubmit"
            :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人" prop="processingPerson">
              <el-input v-model="updateForm.processingPerson" placeholder="请填写处理人" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" class="greenBtn" size="mini" @click="addedSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import posts from "@/plugins/request";
import { mapActions, mapGetters, mapMutations } from "vuex";
import myPaging from "@/components/myPaging.vue";
import common from "@/plugins/common";
import standard from "@/plugins/standard";
export default {
  name: "warningAdmin",
  data() {
    return {
      msg: "hello warningAdmin!",
      warningAdminLoading: false,
      receUserLoading: false,
      searchForm: {
        waterStation: "",
        warningType: "",
        starttime: "",
        lasttime: "",
      },
      updateFormVisible: false,
      addFormData: {},
      updateFormLoading: false,
      updateForm: {
        warningId: "",
        processingMark: "",
        processingPerson: "",
        photoFiles: [],
      },
      updateFormRules: {
        processingMark: [
          { required: true, message: "请输入处理描述", trigger: "blur" },
        ],
        processingPerson: [
          { required: true, message: "请输入处理人", trigger: "blur" },
        ],
        photoFiles: [
          { required: true, message: "请选择照片", trigger: "change" },
        ],
      },
      warnCntVisible: false,
      curWarnCntDetail: {
        warningId: "",
        warningStation: "",
        warningTime: "",
        content: [],
      },

      isHandledVisible: false,
      curIsHandledDetail: {},

      warningStatus: {
        0: "待处理",
        1: "正在处理",
        2: "已处理",
        3: "无",
      },
      warningTypes: [],
      isBatchHandle: false, //是否是批量处理模式
      multipleSelection: [],

      common,
      standard,
    };
  },
  methods: {
    ...mapActions([
      "fetchWarningAdminList",
      "updateWarningAdmin",
      "updateWarningAdminBatch",
      "responseWarningAdmin",
    ]),
    ...mapMutations(["changePageNum"]),
    async onSubmit(pageOption = { pageSize: this.pageSize, pageNum: 1 }) {
      this.warningAdminLoading = true;
      await this.fetchWarningAdminList({ ...this.searchForm, ...pageOption });
      this.warningAdminLoading = false;
    },
    pageUpdate(option) {
      this.onSubmit(option);
    },
    async responseWarning(id) {
      //响应预警
      let result = await this.responseWarningAdmin({ id });
      if (result.message !== "success") {
        this.$notify({
          type: "warning",
          title: "提示",
          message: result.info,
        });
      } else {
        this.$notify({
          type: "success",
          title: "成功",
          message: "预警已响应，请尽快上传完成处理并提交处理结果！",
        });
        this.warnCntVisible = false;
        this.onSubmit();
      }
    },
    async addedSubmit() {
      this.$refs["updateForm"].validate(async (valid) => {
        if (valid) {
          if (this.updateForm.photoFiles.length > 0) {
            this.updateFormLoading = true;
            this.addFormData = new FormData();
            let updateForm = this.updateForm;
            this.$refs.addUploadPhoto.submit();
            for (let i in updateForm) {
              this.loopAppend(this.addFormData, i, updateForm[i]);
            }
            let result = {};
            // 用isBatchHandle判断是否为批量处理模式
            if (this.isBatchHandle) {
              //批量处理模式
              this.addFormData.append(
                "warningIdList",
                this.findNoHandel(this.multipleSelection)
              );
              result = await this.updateWarningAdminBatch(this.addFormData);
            } else {
              //单条处理模式
              return;
              result = await this.updateWarningAdmin(this.addFormData);
            }
            if (result.message !== "success") {
              this.$notify({
                type: "warning",
                title: "提示",
                message: result.info,
              });
            } else {
              this.$notify({
                type: "success",
                title: "成功",
                message: result.info,
              });
              this.$refs["updateForm"].resetFields();
              this.updateFormVisible = false;
              this.changeBatchHandle(false);
              this.changePageNum(1);
              this.onSubmit();
            }
            this.updateFormLoading = false;
          } else {
            this.$notify.warning({
              title: "警告",
              message: "最少上传1张图片",
            });
          }
        } else {
          return false;
        }
      });
    },
    added(id) {
      this.updateForm.warningId = id;
      this.updateForm.processingPerson = this.userInfo.user.username;
      this.updateFormVisible = true;
    },
    uploadChange(file, fileList) {
      this.updateForm.photoFiles = fileList;
    },
    uploadExceed() {
      this.$notify.warning({
        title: "警告",
        message: "最多上传4张图片",
      });
    },
    handleSubmit(response) {
      this.addFormData.append("files", response.file);
    },
    loopAppend(formData, key, value) {
      formData.append(key, value);
    },
    openDetail(id) {
      let curWarning = this.warningAdmin.data.find((v) => v.warningId === id);
      this.curWarnCntDetail.warningStation = curWarning.warningStation;
      this.curWarnCntDetail.warningTime = curWarning.warningTime;
      this.curWarnCntDetail.warningType = curWarning.warningType;
      this.curWarnCntDetail.warningId = id;
      this.curWarnCntDetail.content = [];
      let curContent = curWarning.warningContent;
      for (let i in curContent) {
        this.curWarnCntDetail.content.push({
          name: i,
          value: curContent[i] * 1 ? curContent[i] * 1 : curContent[i],
        });
      }
      this.warnCntVisible = true;
    },
    openIsHandled(id) {
      this.curIsHandledDetail = this.warningAdmin.data.find(
        (v) => v.warningId === id
      );
      let imgList = [];
      if (this.curIsHandledDetail.livePhoto) {
        imgList = this.curIsHandledDetail.livePhoto.split(",");
        imgList.pop();
      }
      this.curIsHandledDetail.imgList = imgList.length ? imgList : [];
      this.isHandledVisible = true;
    },
    indexOFShowUnit(val) {
      let map = [
        "pH",
        "总镍监测设备",
        "总铬监测设备",
        "总氮监测设备",
        "总磷监测设备",
        "总铜监测设备",
        "总氰化物监测设备",
        "氨氮监测设备",
        "pH监测设备",
        "设备异常",
        "总镍设备告警",
        "总铬设备告警",
        "总氮设备告警",
        "总磷设备告警",
        "总铜设备告警",
        "总氰化物设备告警",
        "氨氮设备告警",
        "pH设备告警",
        "系统设备告警",
        "COD设备告警",
      ];
      return !map.includes(val);
    },
    clearUpdateForm() {
      this.$refs.updateForm.resetFields();
    },
    changeBatchHandle(flag) {
      //修改批量处理模式
      this.isBatchHandle = flag;
      if (!flag) this.toggleSelection();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.warningTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.warningTable.clearSelection();
      }
    },
    checkSelectable(row) {
      let multipleSelection = this.multipleSelection;
      if (multipleSelection.length > 0) {
        let firstWarning = this.warningAdmin.data.find(
          (v) => v.warningId === multipleSelection[0]
        );
        return (
          row.warningType === firstWarning.warningType &&
          Math.abs(
            new Date(row.warningTime).getTime() -
              new Date(firstWarning.warningTime).getTime()
          ) <=
            1000 * 60 * 60 * 6
        );
      }
      return true;
    },
    selectAll(selection) {
      let arr = [];
      for (let i = 0; i < selection.length; i++) {
        if (this.checkSelectable(selection[i])) {
          arr.push(selection[i]);
        }
      }
      this.toggleSelection();
      this.toggleSelection(arr);
    },
    selectionChange(val) {
      this.multipleSelection = val.map((v) => v.warningId);
    },
    checkCanSelect({ row }) {
      return this.checkSelectable(row)
        ? { "background-color": "#fff" }
        : { "background-color": "#f5f7fa" };
    },
    batchHandle() {
      let multipleSelection = this.multipleSelection;
      if (multipleSelection.length < 1) {
        this.$notify({
          type: "warning",
          message: "请选择可处理的预警！",
          title: "提醒",
        });
        return;
      }
      this.changeBatchHandle(true);
      this.updateForm.processingPerson = this.userInfo.user.username;
      this.updateFormVisible = true;
    },
    findNoHandel(multipleSelection) {
      let result = [];
      for (let i = 0; i < multipleSelection.length; i++) {
        let curWarning = this.warningAdmin.data.find(
          (v) => v.warningId === multipleSelection[i]
        );
        if (curWarning.warningStatus < 2) {
          result.push(curWarning.warningId);
        }
      }
      return result;
    },
  },
  async created() {
    this.warningTypes = await posts.fetchWarningTypes();

    this.searchForm.starttime = common.changeDateToString(
      new Date(new Date().getTime() - 2592000000)
    );
    this.searchForm.lasttime = common.changeDateToString(new Date());
    this.searchForm.warningType = this.warningTypes[0];

    if ("waterStation" in this.$route.query) {
      this.searchForm.waterStation = this.$route.query.waterStation;
    }
    if ("warningType" in this.$route.query) {
      this.searchForm.warningType = this.$route.query.warningType;
    }
    this.onSubmit();
  },
  computed: {
    ...mapGetters({
      stationList: "getStationList",
      warningAdmin: "getWarningAdmin",
      userInfo: "getUserInfo",

      //分页依赖
      pageSize: "getPageSize",
    }),
  },
  components: {
    myPaging,
  },
};
</script>
<style scoped>
.warningAdmin {
  background: #fff;
  min-height: 100%;
  padding: 0 20px 0 20px;
}
.warningAdmin .title {
  position: relative;
  left: 15px;
  line-height: 70px;
  font-size: 16px;
}
.warningAdmin .title::before {
  content: "";
  position: absolute;
  left: -15px;
  width: 4px;
  height: 20px;
  top: 25px;
  background-color: #2399ff;
}
.searchBox {
  background: #fff;
  margin-bottom: 15px;
}
.searchBox .line {
  text-align: center;
}
.warningAdmin .imgItem {
  max-width: 200px;
  margin-right: 15px;
}
.responseCnt {
  width: 100%;
  padding-top: 20px;
  overflow: hidden;
}
.responseCnt button {
  float: right;
}
.missWarning {
  line-height: 26px;
  font-size: 16px;
}
.openDetailBtn:visited {
  color: red;
}
</style>
<style>
.dangerText.el-button--text {
  color: #e53139;
}
.dangerText.el-button--text:focus,
.dangerText.el-button--text:hover {
  color: #ff9393;
  border-color: transparent;
  background-color: transparent;
}
.el-table-column--selection .cell {
  padding-right: 10px;
}
</style>

